package services

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/pkg/db/mysql"
	"time"
)

type TopicUserRecordService struct {
}

type AnalysisResponse struct {
	List []struct {
		UpIndex    string    `json:"up_index"`
		UserId     string    `json:"user_id"`
		ProjectId  string    `json:"project_id"`
		RealName   string    `json:"real_name"`
		JoinDate   time.Time `json:"join_date"`
		TeamNumber string    `json:"team_number"`
		Phone      string    `json:"phone"`
		Submit     int       `json:"submit"`
		GiveUp     int       `json:"give_up"`
		Get        int       `json:"get"`
		Sg         float64   `json:"sg"`
	} `json:"list"`
	Count int64 `json:"count"`
}

func (t *TopicUserRecordService) UserProjectAnalysis(page, pageSize int, wheres []string) (result AnalysisResponse, err error) {
	_db := mysql.GetDB()
	subQuery := _db.Model(&dao.TopicUserRecord{}).Select("user_id,project_id,tp,COUNT(1) as tp_count").Group("user_id,project_id,tp")
	subQuery2 := _db.Table("(?) as u", subQuery).Select("u.user_id,u.project_id,MAX(case u.tp when 0 then u.tp_count else 0 end) as 'give_up',MAX(case u.tp when 1 then u.tp_count else 0 end) as 'get',MAX(case u.tp when 2 then u.tp_count else 0 end) as 'submit'").Group("u.user_id,u.project_id")
	tx := _db.Table("(?) as us", subQuery2).Select("CONCAT(us.user_id,'@',us.project_id) as up_index,us.*,tas_system_user.real_name,tas_system_user.team_number,tas_system_user.created_at as join_date,tas_system_user.phone,TRUNCATE(us.submit*100/us.get, 2) as sg")
	tx = tx.Joins("left join tas_system_user on us.user_id = tas_system_user.user_id")

	for _, where := range wheres {
		tx = tx.Where(where)
	}

	_db.Table("(?) as t", tx).Count(&result.Count)
	if result.Count == 0 {
		result.List = []struct {
			UpIndex    string    `json:"up_index"`
			UserId     string    `json:"user_id"`
			ProjectId  string    `json:"project_id"`
			RealName   string    `json:"real_name"`
			JoinDate   time.Time `json:"join_date"`
			TeamNumber string    `json:"team_number"`
			Phone      string    `json:"phone"`
			Submit     int       `json:"submit"`
			GiveUp     int       `json:"give_up"`
			Get        int       `json:"get"`
			Sg         float64   `json:"sg"`
		}{}
		return
	}
	if pageSize > 0 {
		tx.Offset((page - 1) * pageSize).Limit(pageSize).Find(&result.List)
	} else {
		tx.Find(&result.List)
	}
	return
}
